/*
 * @Author: yanjikun
 * @Date: 2022-03-21 11:13:21
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-03-23 17:18:27
 * @Description: file content
 */

import { cloneDeep } from 'lodash'
import { computed, ComputedRef, reactive, ref, SetupContext, unref } from 'vue'
import { BasicProps } from '../props'
import { FormActionType, FormConfig } from '../types/form'
import { formActionPropsType } from '../types/formAction'

export type FormState = ReturnType<typeof useFormState>

export type useFormStateParams = {
  props: BasicProps
  attrs: SetupContext['attrs']
}

export const useFormState = ({ props, attrs }: useFormStateParams) => {
  /**
   * TODO 将formProps克隆一份，避免修改原有的formProps
   */
  const formPropsRef = ref<BasicProps>(cloneDeep(props))
  /** 表单项数据  */
  const formModel = reactive({ ...props.initialValues })
  /**表单默认数据 */
  const defaultFormValues = reactive({ ...props.initialValues })
  /**表单实例 */
  const basicFormRef = ref<Nullable<FormActionType>>(null)
  /**操作项默认值 */
  const advanceState = reactive<formActionPropsType>({
    isAdvanced: true,
    showAdvancedButton: false,
    actionSpan: 6
  })
  /**获取表单所有属性 */
  const getFormProps = computed(() => {
    return { ...formPropsRef.value, ...attrs } as BasicProps
  })
  /**获取栅栏Row配置 */
  const getRowConfig = computed(() => {
    const { rowProps, baseRowStyle = {} } = unref(getFormProps)
    const defaultRowProps = {
      gutter: 8
    }
    return {
      style: baseRowStyle,
      ...defaultRowProps,
      ...rowProps
    }
  })
  /**获取操作项所有属性及设置默认值 */
  const getFormActionBindProps = computed(
    (): Recordable => ({ ...getFormProps.value, ...advanceState })
  )
  return {
    formPropsRef,
    formModel,
    defaultFormValues,
    basicFormRef,
    getFormProps,
    getRowConfig,
    advanceState,
    getFormActionBindProps,
    formConfigRef: computed(() => unref(formPropsRef).config ?? []) as ComputedRef<FormConfig[]>
  }
}
